﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SSABSZ.SuperEP.Core;

namespace SSABSZ.SuperEP.Data
{
    public static class DataLayerManager
    {
        static HVCProfileDataContext mySCMDB;
        static ConnectionAddress connectionAddress;

        public static void Initialize(ConnectionAddress vConnectionAddress)
        {
            connectionAddress = vConnectionAddress;
        }

        public static HVCProfileDataContext SCMLINQConnection
        {
            get
            {
                if (mySCMDB == null) // TODO if connection broken reinitialise
                    mySCMDB = new HVCProfileDataContext(ConnectionBuilder(connectionAddress));
                return mySCMDB;
            }
        }

        private static string ConnectionBuilder(ConnectionAddress sqlConnection)
        {
            if (sqlConnection.NTLMAuth)
                return DataLayerManager.ConnectionBuilder(sqlConnection.ServerAddress, sqlConnection.Database);
            else
                return DataLayerManager.ConnectionBuilder(sqlConnection.ServerAddress, sqlConnection.Database, sqlConnection.Username, sqlConnection.Password);
        }
        private static string ConnectionBuilder(string ServerAddress, string Database)
        {
            var connbuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();
            connbuilder.DataSource = ServerAddress;
            connbuilder.InitialCatalog = Database;
            return connbuilder.ConnectionString;
        }

        private static string ConnectionBuilder(string ServerAddress, string Database, string Username, string Password)
        {
            var connbuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();
            connbuilder.DataSource = ServerAddress;
            connbuilder.InitialCatalog = Database;
            connbuilder.UserID = Username;
            connbuilder.Password = Password;
            /*
            connbuilder.DataSource = SettingsHolder.GetValue(Constants.BaseRegPath, "Service\\Database", "DataSource", @"VCRDESIGN04,1433\SQL2012");
            connbuilder.InitialCatalog = SettingsHolder.GetValue(Constants.BaseRegPath, "Service\\Database", "InitialCatalog", "H12");
            var boolParse = false;
            Boolean.TryParse(
                SettingsHolder.GetValue(Constants.BaseRegPath, "Service\\Database", "IntegratedSecurity", "False"),
                out boolParse
                );
            connbuilder.UserID = SettingsHolder.GetValue(Constants.BaseRegPath, "Service\\Database", "UserID", "sa");
            connbuilder.Password = SettingsHolder.GetValue(Constants.BaseRegPath, "Service\\Database", "Password", "mssqlsa");
            connbuilder.IntegratedSecurity = boolParse;
             * */
            return connbuilder.ConnectionString;            
        }
    }
}
